package cn.sinata.wanglin.village.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.HFRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DensityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.TimeUtils;
import com.xilada.xldutils.utils.Utils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;

import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.CommentBean;
import cn.sinata.wanglin.model.ImgBean;
import cn.sinata.wanglin.model.LikeData;
import cn.sinata.wanglin.model.TuCaoAndSameCityDetailInfo;
import cn.sinata.wanglin.neighbor.activity.ApplyFriendOrGroupActivity;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.EMUtils;
import cn.sinata.wanglin.utils.ExpUtils;
import cn.sinata.wanglin.utils.RecyclerListWithFramLayoutActivity;
import cn.sinata.wanglin.utils.ShareConfig;
import cn.sinata.wanglin.utils.ShareUtils;
import cn.sinata.wanglin.utils.StringToUtils;

/**
 * 吐槽和八卦的详情
 */
public class MakecomplaintsdetailActivity extends RecyclerListWithFramLayoutActivity {
    private RecyclerView rv_showphoto;//显示照片的list
    private SimpleDraweeView iv_headview;//头像
    private TextView tv_username;//用户名
    private TextView tv_industry;//行业
    private TextView tv_lable;//归属标签
    private TextView tv_sexoldaddress;//性别年龄小区
    private TextView tv_addfriend;//添加好友
    private TextView tv_content;//内容
    private TextView tv_seenum;//浏览量
    private TextView tv_commentnum;//评论量
    private TextView tv_zannum;//点赞量
    private TextView tv_pubtime;//发布时间
    private TextView tv_zannum_action;//点赞操作
    private TextView tv_gotocomment;//拉起评论操作

    private BaseRecyclerAdapter showphotoAdapter;
    private ArrayList<ImgBean> showphotodatas = new ArrayList<>();
    private HFRecyclerAdapter showCommentAdapter;
    private ArrayList<CommentBean> showCommentdatas = new ArrayList<CommentBean>();
    private int imgwith;
    private String type = null;//类型1 小区吐槽 2同城八卦
    private String externalType = null;//类型（A:八卦，B:吐槽）
    private String id = null;//内容id
    private int pageNo = 0;
    private String friendID = null;
    private String friendAccount = null;
    private String  isanonymity=null;
    @Override
    protected RecyclerView.Adapter setAdapter() {
        if (showCommentAdapter == null) {
            imgwith = DensityUtil.getDeviceWidth(mContext);
            showCommentAdapter = new HFRecyclerAdapter<CommentBean>(showCommentdatas, R.layout.item_commentlist) {
                @Override
                public void onBind(final int position, final CommentBean data, ViewHolder holder) {
                    if (!TextUtils.isEmpty(data.getIsanonymity())) {
                        if ("1".equals(data.getIsanonymity())) {
                            ((SimpleDraweeView) holder.bind(R.id.iv_headview)).setImageURI(Uri.parse("res://mipmap/" + R.mipmap.ic_isanonymity));
                        } else {
                            ((SimpleDraweeView) holder.bind(R.id.iv_headview)).setImageURI(data.getHeadUrl());
                        }
                    } else {
                        ((SimpleDraweeView) holder.bind(R.id.iv_headview)).setImageURI(data.getHeadUrl());
                    }
                    holder.bind(R.id.iv_headview).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if("1".equals(data.getIsanonymity())){
                                return;
                            }
                            ActivityUtil.create(mContext).go(AllUserInfoActivity.class).put("friendID",data.getUserID())
                                    .start();

                        }
                    });

                    if (!TextUtils.isEmpty(data.getUserName())) {
                        holder.setText(R.id.tv_username, data.getUserName());
                    } else {
                        holder.setText(R.id.tv_username, "开心网邻用户");
                    }
                    if (!TextUtils.isEmpty("" + data.getCreateDate())) {
                        holder.setText(R.id.tv_time, TimeUtils.getMilliTimeYMD(data.getCreateDate()));
                    } else {
                        holder.setText(R.id.tv_time, "暂无时间");
                    }
//                    holder.bind(R.id.tv_username).setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            ActivityUtil.create(mContext)
//                                    .go(EditCommentOtherActivity.class)
//                                    .put("id", id)
//                                    .put("toUser", data.getUserID())
//                                    .put("externalType", externalType)
//                                    .put("commentId",data.getId())
//                                    .put("type",1)
//                                    .put("commentUsername",data.getUserName())
//                                    .startForResult(12);
//                        }
//                    });
                    if (!TextUtils.isEmpty(data.getContent())) {
                        //回复类型（0评论文章,1回复评论）
                        if("1".equals(data.getType())){
                            String commentPerson=data.getParentName()+":";
                            String allcomment="回复"+commentPerson+data.getContent();
                            SpannableStringBuilder builder = new SpannableStringBuilder(allcomment);
                            ForegroundColorSpan blueSpan = new ForegroundColorSpan(getResources().getColor(R.color.blue_15));
                            builder.setSpan(blueSpan,2,2+commentPerson.length(),Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            Spannable span = EaseSmileUtils.getSmiledText(mContext,builder);
                            ((TextView)holder.bind(R.id.tv_content)).setText(span, TextView.BufferType.SPANNABLE);
                        }else{
                            Spannable span = EaseSmileUtils.getSmiledText(mContext,data.getContent());
                            ((TextView)holder.bind(R.id.tv_content)).setText(span, TextView.BufferType.SPANNABLE);
                        }
                    } else {
                        holder.setText(R.id.tv_content, "暂无内容");
                    }

                }
            };
            showCommentAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    ActivityUtil.create(mContext)
                            .go(EditCommentOtherActivity.class)
                            .put("id", id)
                            .put("toUser", showCommentdatas.get(position).getUserID())
                            .put("externalType", externalType)
                            .put("commentId",showCommentdatas.get(position).getId())
                            .put("type",1)
                            .put("commentUsername",showCommentdatas.get(position).getUserName())
                            .startForResult(12);
                }
            });
            View headerView = LayoutInflater.from(this).inflate(R.layout.head_detail_tucao_or_samecity, null);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            headerView.setLayoutParams(params);
            showCommentAdapter.setHeaderView(headerView);
            rv_showphoto = (RecyclerView) headerView.findViewById(R.id.rv_showphoto);//显示照片的list
            iv_headview = (SimpleDraweeView) headerView.findViewById(R.id.iv_headview);//头像
            tv_username = (TextView) headerView.findViewById(R.id.tv_username);//用户名
            tv_industry = (TextView) headerView.findViewById(R.id.tv_industry);//行业
            tv_lable = (TextView) headerView.findViewById(R.id.tv_lable);//归属标签
            tv_sexoldaddress = (TextView) headerView.findViewById(R.id.tv_sexoldaddress);//性别年龄小区
            tv_seenum = (TextView) headerView.findViewById(R.id.tv_seenum);//浏览量
            tv_commentnum = (TextView) headerView.findViewById(R.id.tv_commentnum);//评论量
            tv_zannum = (TextView) headerView.findViewById(R.id.tv_zannum);//点赞量
            tv_pubtime = (TextView) headerView.findViewById(R.id.tv_pubtime);//发布时间
            tv_addfriend = (TextView) headerView.findViewById(R.id.tv_addfriend);//添加好友
            tv_content = (TextView) headerView.findViewById(R.id.tv_content);//内容
            RecyclerView.ItemDecoration defaultItemDecoration = new HorizontalDividerItemDecoration.Builder(this)
                    .colorResId(com.xilada.xldutils.R.color.white)
                    .size(10)
                    .build();
            rv_showphoto.addItemDecoration(defaultItemDecoration);
            rv_showphoto.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            showphotoAdapter = new BaseRecyclerAdapter<ImgBean>(showphotodatas, R.layout.item_showphoto) {
                @Override
                public void onBind(final int position, final ImgBean data, ViewHolder holder) {
                    holder.bind(R.id.iv_showphoto).getLayoutParams().width = imgwith;
                    if(!TextUtils.isEmpty(data.getScale())){
                         holder.bind(R.id.iv_showphoto).getLayoutParams().height = LinearLayoutCompat.LayoutParams.WRAP_CONTENT;
                         float temp=Float.parseFloat(data.getScale());
                        ((SimpleDraweeView) holder.bind(R.id.iv_showphoto)).setAspectRatio(temp);
                    }else{
                         holder.bind(R.id.iv_showphoto).getLayoutParams().height =500;
                    }




                    ((SimpleDraweeView) holder.bind(R.id.iv_showphoto)).setImageURI(data.getImgUrl());
                }
            };
            rv_showphoto.setAdapter(showphotoAdapter);
            iv_headview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TextUtils.isEmpty(friendID)) {
                       return;
                    }
                    if("1".equals(isanonymity)){
                        return;
                    }
                    ActivityUtil.create(mContext).go(AllUserInfoActivity.class).put("friendID",friendID)
                            .start();

                }
            });
        }

        return showCommentAdapter;
    }

    private void setData(final TuCaoAndSameCityDetailInfo data) {
        isanonymity= data.getIsanonymity();
        friendAccount = data.getAccount();
        //当前用户是否点赞 1：点过 0：没点
        if (!TextUtils.isEmpty(data.getClickPraise()) && "1".equals(data.getClickPraise())) {
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.ic_zannum2);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_zannum_action.setCompoundDrawables(img_off, null, null, null); //设置右图标
            tv_zannum_action.setTextColor(getResources().getColor(R.color.app_theme_color));
        } else {
            Resources res = getResources();
            Drawable img_off = res.getDrawable(R.mipmap.ic_zannum1);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            tv_zannum_action.setCompoundDrawables(img_off, null, null, null); //设置右图标
            tv_zannum_action.setTextColor(getResources().getColor(R.color.textColorHint));
        }
        friendID = data.getUserId();
        if (!TextUtils.isEmpty(data.getIsanonymity())) {
            if ("1".equals(data.getIsanonymity())) {
                iv_headview.setImageURI(Uri.parse("res://mipmap/" + R.mipmap.ic_isanonymity));
            } else {
                iv_headview.setImageURI(data.getHeadUrl());
            }
        } else {
            iv_headview.setImageURI(data.getHeadUrl());
        }
        if (!TextUtils.isEmpty(data.getName())) {
            tv_username.setText(data.getName());//用户名
        } else {
            tv_username.setText(Constant.DEFULT_NICKNAME);//用户名
        }
        switch (ExpUtils.getExpValue(data.getExp())){

            case 1:
                Resources res1 = mContext.getResources();
                Drawable img_off1 = res1.getDrawable(R.mipmap.ic_exp1);
                img_off1.setBounds(0, 0, img_off1.getMinimumWidth(), img_off1.getMinimumHeight());
                tv_username.setCompoundDrawables(null, null, img_off1, null); //设置右图标
                break;
            case 2:
                Resources res2 = mContext.getResources();
                Drawable img_off2 = res2.getDrawable(R.mipmap.ic_exp2);
                img_off2.setBounds(0, 0, img_off2.getMinimumWidth(), img_off2.getMinimumHeight());
                tv_username.setCompoundDrawables(null, null, img_off2, null); //设置右图标
                break;
            case 3:
                Resources res3 = mContext.getResources();
                Drawable img_off3 = res3.getDrawable(R.mipmap.ic_exp3);
                img_off3.setBounds(0, 0, img_off3.getMinimumWidth(), img_off3.getMinimumHeight());
                tv_username.setCompoundDrawables(null, null, img_off3, null); //设置右图标
                break;
            case 4:
                Resources res4 = mContext.getResources();
                Drawable img_off4 = res4.getDrawable(R.mipmap.ic_exp4);
                img_off4.setBounds(0, 0, img_off4.getMinimumWidth(), img_off4.getMinimumHeight());
                tv_username.setCompoundDrawables(null, null, img_off4, null); //设置右图标
                break;
            case 5:
                Resources res5 = mContext.getResources();
                Drawable img_off5 = res5.getDrawable(R.mipmap.ic_exp5);
                img_off5.setBounds(0, 0, img_off5.getMinimumWidth(), img_off5.getMinimumHeight());
                tv_username.setCompoundDrawables(null, null, img_off5, null); //设置右图标
                break;
            case 6:
                Resources res6 = mContext.getResources();
                Drawable img_off6 = res6.getDrawable(R.mipmap.ic_exp6);
                img_off6.setBounds(0, 0, img_off6.getMinimumWidth(), img_off6.getMinimumHeight());
                tv_username.setCompoundDrawables(null, null, img_off6, null); //设置右图标
                break;
        }
        if (!TextUtils.isEmpty(data.getIndustry())) {
            tv_industry.setText(data.getIndustry());//行业
        } else {
            tv_industry.setText("暂无");//行业
        }
        if (!TextUtils.isEmpty(data.getBelongLabel())) {
            tv_lable.setText(data.getBelongLabel());//归属标签
        } else {
            tv_lable.setText("暂无");//归属标签
        }
        StringBuffer sexoldaddress = new StringBuffer();
        if (!TextUtils.isEmpty(data.getSex())&&"0".equals(data.getSex())) {
            //为男。
            sexoldaddress.append("男");//拼接性别
            sexoldaddress.append("\u3000");
        } else {
            sexoldaddress.append("女");//拼接性别
            sexoldaddress.append("\u3000");
        }
        if (!TextUtils.isEmpty(data.getBirthday())) {
            sexoldaddress.append(StringToUtils.toOld(data.getBirthday()));
            sexoldaddress.append("\u3000");//岁数区间
        }
        if (!TextUtils.isEmpty(data.getHousingName())) {
            sexoldaddress.append(data.getHousingName());
            sexoldaddress.append("\u3000");//小区名字
        }
        if (!TextUtils.isEmpty(sexoldaddress.toString())) {
            tv_sexoldaddress.setText(sexoldaddress.toString());//性别年龄小区
        } else {
            tv_sexoldaddress.setText("暂无");//性别年龄小区
        }
        if (!TextUtils.isEmpty(data.getBrowses())) {
            tv_seenum.setText(data.getBrowses());//浏览量
        } else {
            tv_seenum.setText("0");//浏览量
        }
        if (!TextUtils.isEmpty(data.getCommentCount())) {
            tv_commentnum.setText(data.getCommentCount());//评论量
        } else {
            tv_commentnum.setText("0");//评论量
        }
        if (!TextUtils.isEmpty(data.getLikes())) {
            tv_zannum.setText(data.getLikes());//点赞量
            tv_zannum_action.setText(data.getLikes());//点赞量
        } else {
            tv_zannum_action.setText("0");//点赞量
            tv_zannum.setText("0");//点赞量
        }

        Utils.systemErr("--data.getCreateDate()--" + data.getCreateDate());
        tv_pubtime.setText("发布于:" + TimeUtils.getMilliTimeYMD(data.getCreateDate()));//发布时间
        String userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
        if (!TextUtils.isEmpty(data.getUserId()) && userid.equals(data.getUserId())) {
            tv_addfriend.setVisibility(View.GONE);
        } else {
            tv_addfriend.setVisibility(View.VISIBLE);
        }
        //是否是好友是否是好友(0：不是好友，1:已经是好友，2：待同意)
        if (!TextUtils.isEmpty(data.getIsFriends())) {
            if ("0".equals(data.getIsFriends())) {
                tv_addfriend.setText("加好友");
            } else if ("1".equals(data.getIsFriends())) {
                tv_addfriend.setText("取消好友");
            } else if ("2".equals(data.getIsFriends())) {
                tv_addfriend.setText("待同意");
            }
        }

        if (!TextUtils.isEmpty(data.getContent())) {
            tv_content.setText(EaseSmileUtils.getSmiledText(mContext,data.getContent()));//内容
        } else {
            tv_content.setText("暂无内容");//浏览量
        }
        if (data.getImg() != null && data.getImg().size() != 0) {
            showphotodatas.clear();
            showphotodatas.addAll(data.getImg());
            showphotoAdapter.notifyDataSetChanged();
        }
        if (pageNo == 0) {
            showCommentdatas.clear();
        }
        if (data.getComment() == null || data.getComment().size() == 0) {
            if (pageNo == 0) {
                setLoadMoreText("暂无数据");
            } else {
                pageNo--;
                setLoadMoreText("没有更多了");
            }
        }
        if (data.getComment() != null) {
            showCommentdatas.addAll(data.getComment());
        }
        showCommentAdapter.notifyDataSetChanged();

        tv_addfriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("0".equals(data.getIsFriends())) {
                    ActivityUtil.create(mContext)
                            .go(ApplyFriendOrGroupActivity.class)
                            .put("id",friendID)
                            .startForResult(66);
                }else if("1".equals(data.getIsFriends())){
                    cancelFriend();
                }
            }
        });
    }
    void cancelFriend(){

        showDialog();
        String userid=SharedPreferencesUtils.getString(Constant.SP_USERID);
        HttpManager.cancelFriend(userid,friendID)
                .subscribe(new ResultDataSubscriber<JsonObject>(this) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        EMUtils.deleteConversation(friendAccount);
                        showToast(msg);
//                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }
    @Override
    protected void initView() {
        super.initView();
        View flView = LayoutInflater.from(this).inflate(R.layout.bottom_comment_and_zan, null);
        tv_gotocomment = (TextView) flView.findViewById(R.id.tv_gotocomment);
        tv_zannum_action = (TextView) flView.findViewById(R.id.tv_zannum_action);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.BOTTOM;
        getFl_prent_list().addView(flView, params);
        type = getIntent().getStringExtra("type");
        id = getIntent().getStringExtra("id");
        if ("1".equals(type)) {
            setTitle("吐槽详情");
            externalType = "B";
        } else if ("2".equals(type)) {
            setTitle("八卦详情");
            externalType = "A";
        }
        addRightButton(R.mipmap.ic_shareto, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url=ShareConfig.shareToApp(type,id);
                ShareUtils.share(MakecomplaintsdetailActivity.this,""+tv_content.getText().toString(),"开心网邻",url);
            }
        });
        tv_gotocomment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(friendID)) {
                    ActivityUtil.create(mContext)
                            .go(EditCommentOtherActivity.class)
                            .put("id", id)
                            .put("toUser", friendID)
                            .put("externalType", externalType)
                            .startForResult(12);
                } else {
                    showToast("拉取评论失败！");
                }

            }
        });
        tv_zannum_action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
                praise();
            }
        });
        showDialog();
        getData();
    }

    private void getData() {
        String userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
        HttpManager.getTuCaoOrSameCityDetail(userid, id, type, pageNo).subscribe(new ResultDataSubscriber<TuCaoAndSameCityDetailInfo>(this) {
            @Override
            public void onSuccess(String msg, TuCaoAndSameCityDetailInfo tuCaoAndSameCityDetailInfo) {
                mSwipeRefreshLayout.setRefreshing(false);
                setData(tuCaoAndSameCityDetailInfo);

            }
        });
    }

    @Override
    protected void pullDownRefresh() {
        super.pullDownRefresh();
        pageNo = 0;
        getData();
    }

    @Override
    protected void loadMore() {
        super.loadMore();
        pageNo++;
        getData();
    }

    private void praise() {
        String userid = SharedPreferencesUtils.getString(Constant.SP_USERID);
        HttpManager.clickPraise(userid, externalType, id)
                .subscribe(new ResultDataSubscriber<LikeData>(this) {
                    @Override
                    public void onSuccess(String msg, LikeData likeData) {
                        showToast(msg);
                        int num = Integer.parseInt(tv_zannum_action.getText().toString());
                        //当前用户行为 1：取消点赞 0：点赞
                        if (likeData.getClickPraise() == 0) {
                            num++;
                            tv_zannum_action.setText("" + num);
                            tv_zannum.setText("" + num);
                            Resources res = getResources();
                            Drawable img_off = res.getDrawable(R.mipmap.ic_zannum2);
                            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                            tv_zannum_action.setCompoundDrawables(img_off, null, null, null); //设置右图标
                            tv_zannum_action.setTextColor(getResources().getColor(R.color.app_theme_color));
                        } else {
                            num--;
                            tv_zannum_action.setText("" + num);
                            tv_zannum.setText("" + num);
                            Resources res = getResources();
                            Drawable img_off = res.getDrawable(R.mipmap.ic_zannum1);
                            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                            tv_zannum_action.setCompoundDrawables(img_off, null, null, null); //设置右图标
                            tv_zannum_action.setTextColor(getResources().getColor(R.color.textColorHint));
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 12:
                    showDialog();
                    pullDownRefresh();
                    break;
                case 66:
                    showDialog();
                    pullDownRefresh();
                    break;
            }

        }
    }
}
